import { loginApi, logoutApi, getUserInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import router, { resetRouter } from '@/router'
import router from '@/router'

const state = {
    userToken: getToken(),
    userName: '',
    userAvatar: '',
    userRoles: [],
    userIntroduction: ''
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.userToken = token
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.userIntroduction = introduction
    },
    SET_NAME: (state, name) => {
        state.userName = name
    },
    SET_AVATAR: (state, avatar) => {
        state.userAvatar = avatar
    },
    SET_ROLES: (state, roles) => { 
        state.userRoles = roles
    }
}

const actions = {
    // user login ，用户登录
    login({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            loginApi(userInfo).then(res => {
                if (res.data) {
                    let getToken = res.data.access_token;
                    commit('SET_TOKEN', getToken);
                    setToken(getToken)
                } else {
                    // 
                    /* // 先本地随机生成一个token 用于判断登录
                    let tokenStr = `token_${parseInt(Math.random() * new Date().getTime())}`;
                    console.log(` setToken : ${tokenStr} `)
                    commit('SET_TOKEN', tokenStr)
                    setToken(tokenStr) */
                }
                resolve(res);
            }).catch(error => {
                console.log(error)
                reject(error)
            })
        })

    },

    // get user info，获取用户信息
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            console.log(state)
            getUserInfoApi().then(res => {
                if (res.code != 200) {
                    reject(res.msg || '验证失败，请重新登录。');
                }
                // const { permissions , roles ,user } = res;
                const { roles, user } = res;
                console.log(res)
                let name = user.nickName || '';
                let avatar = user.avatar || 'https://img1.baidu.com/it/u=4275719105,4185078178&fm=253&fmt=auto&app=138&f=JPEG?w=350&h=350'
                console.log(`avatar : ${avatar}`)
                // 添加单点登录了，暂时去掉此处验证
                console.log(`角色：${roles.length}, 此处暂不验证`)
                /* if (!roles || roles.length <= 0) {
                    reject(`getInfo:角色必须是非空数组`)
                } */
                commit('SET_ROLES', roles)
                commit('SET_NAME', name)
                commit('SET_AVATAR', avatar)
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 用户退出登录
    logOut({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            console.log(` state : ${state} ，${commit}, ${dispatch}`)
            logoutApi().then(res => {
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token , 删除缓存的一些用户信息
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
        })
    },

    // dynamically modify permissions
    async changeRoles({ commit, dispatch }, role) {
        const token = role + '-token'
        commit('SET_TOKEN', token)
        setToken(token)
        const { roles } = await dispatch('getInfo')

        // generate accessible routes map based on roles
        const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
        // dynamically add accessible routes
        router.addRoutes(accessRoutes)

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
